package com.danskin.wechat.webapi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; 
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.danskin.wechat.entity.BannerInfo;
import com.danskin.wechat.entity.CustInfoEx;
import com.danskin.wechat.entity.CustItemRecord;
import com.danskin.wechat.entity.CustItemRecordDetail;
import com.danskin.wechat.entity.CustPointRecord;
import com.danskin.wechat.entity.CustShipping;
import com.danskin.wechat.entity.ProductInfo;
import com.danskin.wechat.entity.WxFansInfo;
import com.danskin.wechat.model.AccessResponse;
import com.danskin.wechat.model.BannerInfoDTO;
import com.danskin.wechat.model.ConfirmOrder;
import com.danskin.wechat.model.CustItemRecordDTO;
import com.danskin.wechat.model.CustItemRecordDTOTO;
import com.danskin.wechat.model.CustItemRecordDetailDTO;
import com.danskin.wechat.model.CustPointRecordDTO;
import com.danskin.wechat.model.CustPointResponse;
import com.danskin.wechat.model.CustShippingDTO;
import com.danskin.wechat.model.ProductInfoDTO;
import com.danskin.wechat.model.ProductInfoDetailDTO;
import com.danskin.wechat.model.ProductInfoIntegralDTO;
import com.danskin.wechat.model.ProductInfoTypeDTO;
import com.danskin.wechat.service.BannerInfoService;
import com.danskin.wechat.service.CustInfoExService;
import com.danskin.wechat.service.CustItemRecordDetailService;
import com.danskin.wechat.service.CustItemRecordService;
import com.danskin.wechat.service.CustPointRecordService;
import com.danskin.wechat.service.CustShippingService;
import com.danskin.wechat.service.ProductInfoService;
import com.danskin.wechat.service.SysAreaService;
import com.danskin.wechat.util.ConvertUtils;
import com.danskin.wechat.util.Page;

/****
 * 积分商城接口
 * @author admin
 *
 */
@RestController
@RequestMapping("api/integralMall")
public class IntegralMallController extends BaseApiController{
	@Autowired
	private CustPointRecordService custPointRecordService;
	@Autowired
	private CustInfoExService custInfoExService;
	@Autowired
	private ProductInfoService  productInfoService;
	@Autowired
	private CustItemRecordService custItemRecordService;
	@Autowired
	private CustItemRecordDetailService custItemRecordDetailService;
	@Autowired
	private CustShippingService custShippingService;
	@Autowired
	private SysAreaService sysAreaService;
	@Autowired
	private BannerInfoService  bannerInfoService;
	/****
	 * 积分商城获取(总积分，可用积分)
	 * @param appId
	 * @param wxFansInfo
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getCustPointRecordListAPI/{appId}",method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object getCustPointRecordListAPI(@PathVariable("appId") String appId,@RequestBody Map<String, Object> map, HttpServletRequest request) {
		SimpleDateFormat fmt=new SimpleDateFormat("yyyy-MM-dd");
		if (!map.containsKey("type")) {
			return this.getError("积分状态不能为空");
		}else if (!map.containsKey("pageIndex")) {
			return this.getError("pageIndex不能为空");
		}else if (!map.containsKey("openId")) {
			return this.getError("openId不能为空");
		}
		String sType = map.get("type").toString();
		String sPageIndex= map.get("pageIndex").toString();
		int pageIndex = ConvertUtils.getInt(sPageIndex);
		int pageSize = 10;
		map.put("appId", appId);
		Page page = new Page();
		page.setCurrentResult(pageIndex);
		page.setShowCount(pageSize);
		page.setMap(map);
		
		List<CustPointRecord> custPointRecord = custPointRecordService.findCustPointRecordListAPI(page, sType);
		List<CustPointRecordDTO>  list = new ArrayList<CustPointRecordDTO>();
		if(custPointRecord.size()>0){
			for(CustPointRecord dto:custPointRecord){
				CustPointRecordDTO custPointRecordDTO = new CustPointRecordDTO();
				custPointRecordDTO.setTnum(dto.getPoints());
				custPointRecordDTO.setGettamp(fmt.format(dto.getExpiredTime()));
				custPointRecordDTO.setLtamp(fmt.format(dto.getGetTime()));
				list.add(custPointRecordDTO);
			}
		}
		return new AccessResponse<Object>("0", "ok", list);
	}
	
	/****
	 * 积分商城获取(总积分，可用积分)
	 * @param appId
	 * @param wxFansInfo
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getIntegralSum/{appId}",method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object getIntegralSum(@PathVariable("appId") String appId,@RequestBody WxFansInfo wxFansInfo, HttpServletRequest request) {
		CustInfoEx custInfoEx = custInfoExService.queryCustInfoEx(appId,String.valueOf(wxFansInfo.getOpenId()));
		CustPointResponse custPoint = new CustPointResponse();
		if(custInfoEx!=null){ 
			 custPoint.setLastpoints(String.valueOf(custInfoEx.getAvaPoints()));
			 custPoint.setAllpoints(String.valueOf(custInfoEx.getTotalPoints())); 
		}else{
			 custPoint.setLastpoints("0");
			 custPoint.setAllpoints("0"); 
		}
		return new AccessResponse<Object>("0", "ok", custPoint);
	}
	/**
	 * 积分商城(列表)
	 * @param appId
	 * @param wxFansInfo
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "queryProductInfoListAPI/{appId}",method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object queryProductInfoListAPI(@PathVariable("appId") String appId,@RequestBody WxFansInfo wxFansInfo, HttpServletRequest request){
		if(StringUtil.isEmpty(appId)){
			return this.getError("appId不能为空");
		}
        if(StringUtil.isEmpty(wxFansInfo.getOpenId())){
        	return this.getError("openId不能为空");
		}
        List<ProductInfoDTO> dtoList = new ArrayList<ProductInfoDTO>();
		List<ProductInfo> productList = productInfoService.findProductInfoListAPI(appId,String.valueOf(wxFansInfo.getOpenId()));
		if(productList.size()>0){
			for(ProductInfo productInfo:productList){
				ProductInfoDTO dto = new ProductInfoDTO();
				dto.setId(productInfo.getId());
				dto.setPrice(String.valueOf(productInfo.getSalePoints()));
				dto.setTitle(productInfo.getName());
				dto.setImg(productInfo.getImg());
				dtoList.add(dto);
			}
		}
		return new AccessResponse<Object>("0", "ok", dtoList);
	}
	/****
	 * 商品分类查询(当月精选，每月团购)
	 * @return
	 */
	@RequestMapping(value = "queryProductInfoTypeList/{appId}",method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object queryProductInfoTypeList(@PathVariable("appId") String appId,@RequestBody Map<String, Object> map,HttpServletRequest request){
		if (!map.containsKey("openId")) {
			return this.getError("openId不能为空");
		}else if (!map.containsKey("type")) {
			return this.getError("type不能为空");
		}
        String openId = map.get("openId").toString();
		String type = map.get("type").toString();
        List<ProductInfoTypeDTO> dToList = new ArrayList<ProductInfoTypeDTO>();
        List<ProductInfo> productType = productInfoService.findProductInfoListType(appId,openId,type);
        if(productType.size()>0){
			for(ProductInfo productInfo:productType){
				ProductInfoTypeDTO dto = new ProductInfoTypeDTO();
				dto.setId(productInfo.getId());
				dto.setTitle(productInfo.getName());
				dto.setImgUrl(productInfo.getImg());
				dto.setGroupPrice(productInfo.getSalePoints());
				dto.setOriginalPrice(productInfo.getOriginPoints());
				dToList.add(dto);
			}
		} 
        return new AccessResponse<Object>("0", "ok", dToList);
	}
	/***
	 * 商品搜索
	 * @param appId
	 * @param wxFansInfo
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "queryProductInfoListSearch/{appId}",method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object queryProductInfoListSearch(@PathVariable("appId") String appId,@RequestBody Map<String, Object> map, HttpServletRequest request){
		String name = map.get("name").toString();
        List<ProductInfoIntegralDTO> dtoList = new ArrayList<ProductInfoIntegralDTO>();
        String sPageIndex= map.get("pageIndex").toString();
		int pageIndex = ConvertUtils.getInt(sPageIndex);
		int pageSize = 10;
		map.put("appId", appId);
		Page page = new Page();
		page.setCurrentResult(pageIndex);
		page.setShowCount(pageSize);
		page.setMap(map);
		String integral = null;
		String title = null;
		if(isNumeric(name)){
			integral = name;
		}else{
			title = name;
		}
		List<ProductInfo> productList = productInfoService.searchProductInfoList(page,integral,title);
		if(productList.size()>0){
			for(ProductInfo productInfo:productList){
				ProductInfoIntegralDTO dto = new ProductInfoIntegralDTO();
				dto.setId(productInfo.getId());
				dto.setPrice(String.valueOf(productInfo.getSalePoints()));
				dto.setTitle(productInfo.getName());
				dto.setImg(productInfo.getImg());
				dto.setType(String.valueOf(productInfo.getProdType())); 
				dtoList.add(dto);
			}
		}
		return new AccessResponse<Object>("0", "ok", dtoList);
	}
	
	private  boolean isNumeric(String str){
	    Pattern pattern = Pattern.compile("[0-9]*");
	    return pattern.matcher(str).matches();   
	}
	
	/***
	 * 积分商城兑换记录(详细信息)
	 * @param appId
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "queryCustItemRecordDetail/{appId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object queryCustItemRecordDetail(@PathVariable("appId") String appId, @RequestBody Map<String, Object> map,
			HttpServletRequest request) {
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (!map.containsKey("id")) {
			return this.getError("id不能为空");
		}else if (!map.containsKey("openId")) {
			return this.getError("openId不能为空");
		}
		String id = map.get("id").toString();
		String openId = map.get("openId").toString();
		CustItemRecord custItemRecord = custItemRecordService.findCustItemRecordModel(appId, openId, id);
		List<CustItemRecordDetail> listDetail = custItemRecordDetailService.findCustItemRecordDetail(id);
		List<ProductInfo> prod = productInfoService.queryProductInfoType(custItemRecord.getId());
		CustItemRecordDTOTO dto = new CustItemRecordDTOTO();
		try {
			dto.setOid(custItemRecord.getId());
			dto.setOcode(custItemRecord.getOrderNo());
			dto.setOtamp(fmt.format(custItemRecord.getCreatedTime()));
			dto.setOstatus(getFormatStatus(String.valueOf(custItemRecord.getOrderStatus())));
			dto.setOfrom("门店");
			dto.setOfromcode("");
			dto.setOpoints(String.valueOf(custItemRecord.getTotalAmount()));
			dto.setOprice(String.valueOf(custItemRecord.getTotalPoints()));
			dto.setOsaleprice("");
			dto.setOiotprice("");
			dto.setOpayprice(String.valueOf(custItemRecord.getTotalPoints()));
			List<CustItemRecordDetailDTO> children = this.fmtCustItemRecordDetailDTOList(listDetail, prod);
			dto.setDatainfo(children);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new AccessResponse<Object>("0", "ok", dto);
	}
	private List<CustItemRecordDetailDTO> fmtCustItemRecordDetailDTOList(List<CustItemRecordDetail> listDetail,List<ProductInfo> prod){
		List<CustItemRecordDetailDTO> list = new ArrayList<CustItemRecordDetailDTO>();
		if(listDetail.size()>0){
			for(CustItemRecordDetail detail:listDetail){
				for(ProductInfo info:prod){
					if(detail.getProductId()==info.getId()){
						CustItemRecordDetailDTO dto = new CustItemRecordDetailDTO();
						dto.setPid(detail.getId());
						dto.setPimg("");
						dto.setPnum(String.valueOf(detail.getProductQty()));
						dto.setPprice(String.valueOf(detail.getPoints()));
						dto.setPtitle(detail.getProductName());
						if(info.getProdType()==1){
							dto.setPweight("张");
						}else{
							dto.setPweight(detail.getWeight());
						}
						list.add(dto);
					}
				}
			}
		}
		return list;
	}
	/***
	 * 积分商城兑换记录
	 * @param appId
	 * @param wxFansInfo
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "queryExchangeRecord/{appId}",method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object queryExchangeRecord(@PathVariable("appId") String appId,@RequestBody Map<String, Object> map,HttpServletRequest request){
		SimpleDateFormat fmt=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (!map.containsKey("type")) {
			return this.getError("不能为空");
		}else if (!map.containsKey("openId")) {
			return this.getError("openId不能为空");
		}
		String openId = map.get("openId").toString();
		String type = map.get("type").toString();
		
		String sPageIndex= map.get("pageIndex").toString();
		int pageIndex = ConvertUtils.getInt(sPageIndex);
		int pageSize = 10;
		map.put("appId", appId);
		Page page = new Page();
		page.setCurrentResult(pageIndex);
		page.setShowCount(pageSize);
		page.setMap(map);
		
		List<CustItemRecord> custItemRecordList = custItemRecordService.findCustItemRecordList(page,openId,type);
		List<CustItemRecordDTO> dtoList = new ArrayList<CustItemRecordDTO>();
		if(custItemRecordList.size()>0){
			List<Integer> listOrd = new ArrayList<Integer>();
			for(int i=0;i<custItemRecordList.size();i++){
				CustItemRecord record = custItemRecordList.get(i);
				listOrd.add(record.getId());
			}
			List<ProductInfo> details = productInfoService.queryProductInfoByModelId(listOrd);
			/*List<CustItemRecordDetail> list = this.sumQty(listOrd);	*/		
			for(int i=0;i<custItemRecordList.size();i++){
				CustItemRecord itemRecord = custItemRecordList.get(i);
				CustItemRecordDTO dto = new CustItemRecordDTO();
				dto.setOid(itemRecord.getId());
				dto.setOcode(itemRecord.getOrderNo());
				dto.setOtamp(fmt.format(itemRecord.getCreatedTime()));
				dto.setOstatus(getFormatStatus(String.valueOf(itemRecord.getOrderStatus())));
				dto.setOprice(String.valueOf(itemRecord.getTotalPoints()));
				dto.setOnum(custItemRecordDetailService.getCustItemRecordDetail(itemRecord.getId()).getProductQty());
				if(StringUtil.isNotEmpty(itemRecord.getShipperCode())){
					dto.setShipperCode(this.logisticsNameMap().get(itemRecord.getShipperCode()));
				}else{
					dto.setShipperCode(itemRecord.getShipperCode());
				}
				List<CustItemRecordDetailDTO> children = this.getCustItemRecordDetailDTOList(getByItemId(itemRecord.getId(),details),String.valueOf(itemRecord.getId()));
				dto.setDatainfo(children);
				dtoList.add(dto);
			}	
		}
		return new AccessResponse<Object>("0", "ok", dtoList);
	}
	/***
	 * 匹配数据
	 * @param itemId
	 * @param list
	 * @return
	 */
	/*private int getOnum(int itemId, List<CustItemRecordDetail> list ){
		for(CustItemRecordDetail de:list){
			if(itemId==de.getCustItemId()){
				return de.getProductQty();
			}
		}
		return 0;
	}*/
    /***
     * 筛选相同商品
     * @param itemId
     * @param detailDTO
     * @return
     */
	public List<ProductInfo> getByItemId(int itemId, List<ProductInfo> detailDTO) {
		List<ProductInfo> list = new ArrayList<ProductInfo>();
		for (ProductInfo pf : detailDTO) {
			if (itemId == pf.getCustItemId()) {
				list.add(pf);
			}
		}
		return list;
	}
	/***
	 * 数据转化(接口字段与数据库一致性)
	 * @param details
	 * @return
	 */
	public List<CustItemRecordDetailDTO> getCustItemRecordDetailDTOList(List<ProductInfo> details,String id){
		List<CustItemRecordDetailDTO> dto = new ArrayList<CustItemRecordDetailDTO>();
		if(details.size()>0){
			for(ProductInfo pf:details){
				CustItemRecordDetailDTO dt = new CustItemRecordDetailDTO();
				dt.setPid(pf.getId());
				dt.setPimg(pf.getImg());
				dt.setPtitle(pf.getName());
				if(pf.getProdType()==1){
					dt.setPweight("张");
				}else{
					dt.setPweight(this.findCustItemRecordDetail(pf.getId(),id));
				}
				dt.setPnum(pf.getProductQty());
				dt.setPprice(pf.getPoints());
				dto.add(dt);
			}
		}
		return dto;
	}
	/**
	 * 获取商品订单规格
	 * @param pId
	 * @return
	 */
	public String findCustItemRecordDetail(int pId,String custItemId){
		String weight = "";
		List<CustItemRecordDetail> list = custItemRecordDetailService.queryCustItemRecordAll(custItemId);
		if(list.size()>0){
			for(CustItemRecordDetail detail:list){
				if(pId==detail.getProductId()){
					weight = detail.getWeight();
					break;
				}
			}
		}
		return weight;
	}
	/***
	 * 订单状态处理
	 * @param str
	 * @return
	 */
	public String getFormatStatus(String str){
		String status = null;
		if("0".equals(str)){
			status = "待审核";
		}else if("1".equals(str)){
			status = "已审核确认";
		}else if("2".equals(str)){
			status = "审核未通过";
		}else if("3".equals(str)){
			status = "客户已确认(待发货)";
		}else if("4".equals(str)){
			status = "已发货";
		}else if("5".equals(str)){
			status = "已完成";
		}else if("99".equals(str)){
			status = "订单作废";
		}
		return status;
	}
	/*public List<CustItemRecordDetail> sumQty(List<Integer> custItemList){
		return custItemRecordDetailService.getCustItemRecordDetail(custItemList);
	}*/
	/***
	 * 积分商品详情
	 * @param appId
	 * @param wxFansInfo
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "queryProductInfoDetail/{appId}",method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object queryProductInfoDetail(@PathVariable("appId") String appId,@RequestBody Map<String, Object> map, HttpServletRequest request){
		if (!map.containsKey("id")) {
			return this.getError("id不能为空");
		}else if (!map.containsKey("openId")) {
			return this.getError("openId不能为空");
		}
		String id= map.get("id").toString();
		String openId = map.get("openId").toString();
		ProductInfo product = productInfoService.getProductInfoDetail(appId,openId,id);
		ProductInfoDetailDTO dto = null;
		if(product!=null){
			dto = new ProductInfoDetailDTO();
			dto.setId(product.getId());
			dto.setPtype(product.getProdType());
			dto.setTitle(product.getName());
			dto.setPrice(String.valueOf(product.getSalePoints()));
			dto.setLeftnums(String.valueOf(product.getStockQty()));
			dto.setImg(product.getImg());
			if(product.getProdType()==1){
				dto.setWeight("张");
			}else{
				if(StringUtil.isNotEmpty(product.getSpecShoes())){
					dto.setWeight(product.getSpecShoes());
				}
				if(StringUtil.isNotEmpty(product.getClothesSize())){
					dto.setWeight(product.getClothesSize());
				}
			}			
			dto.setIottype("免运费");
			dto.setContent(product.getDetails());
		}
		return new AccessResponse<Object>("0", "ok", dto);
	}
	/***
	 * 确认订单(积分商城)
	 * @param appId
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "saveConfirmOrder/{appId}",method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object saveConfirmOrder(@PathVariable("appId") String appId,@RequestBody JSONObject json, HttpServletRequest request){
		String openId = json.get("openId").toString();
		String address = json.get("address").toString();
		String city = json.get("city").toString();	
		String district = json.get("district").toString();
		String name = json.get("name").toString();
		String phone = json.get("phone").toString();
		String province = json.get("province").toString();
		JSONArray dataLsit = json.getJSONArray("data");
		ConfirmOrder order  = new ConfirmOrder();
		List<Integer> listId = new ArrayList<Integer>();
		if(dataLsit!=null){
			for(int i=0;i<dataLsit.size();i++){
				JSONObject job =  (JSONObject) dataLsit.get(i);
			    String id = job.get("id").toString();
			    listId.add(Integer.parseInt(id));
			}
		}	
		List<ProductInfo> listProductInfo = productInfoService.queryProductInfoByModle(listId);
		//判断积分是否可用
		CustInfoEx ex = custInfoExService.queryCustInfoEx(appId, openId);		
		boolean integral = this.checkProductInfoSalePoints(dataLsit,ex.getAvaPoints(),listProductInfo);		
		if(!integral){
			return new AccessResponse<Object>("-1", "积分不足，请选择其它商品兑换");
		}
		//判断每一个产品是否有充足的库存数量
		String nameQty = this.checkProductInfoQty(dataLsit,listProductInfo);
		if(nameQty!=null){
			return new AccessResponse<Object>("-1", "库存不足，请选择其它商品兑换");
		}
		String  access_token = this.getMPAccessToken(appId);
		//String  accessTokec = "x_e2RX_k6h8c3ElRqETlqLsv53blPfgDQ6Nt__vf8B5VvUuDRtahCzxXef_K5q2B9hKkKHojl2Hmuf7fC_NrFjEVukGeORW8Hxn7jDx-6FI8za6I4V7Nm7j4xFedDaiBFAUiALDYTN";
		try {
			//初始化客户收货信息
			String provincename =  sysAreaService.getSysAreaByCode(province);
			String cityname =  sysAreaService.getSysAreaByCode(city);
			String districtname =  sysAreaService.getSysAreaByCode(district);
			//custShippingService.insertCustShipping(openId,appId,address,city,district,name,phone,province);
			int id = custItemRecordService.insertCustItemRecord(openId,appId,address,cityname,districtname,name,phone,provincename,dataLsit,access_token);			
			order.setId(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new AccessResponse<Object>("0", "成功", order);
	}
	/***
	 * 判断商品库存
	 * @param dataLsit
	 * @return
	 */
	private String checkProductInfoQty(JSONArray dataLsit,List<ProductInfo> listProductInfo){
		List<Integer> listId = new ArrayList<Integer>();
		String strName = null;
		if(dataLsit!=null){
			for(int i=0;i<dataLsit.size();i++){
				JSONObject job =  (JSONObject) dataLsit.get(i);
			    String id = job.get("id").toString();
			    String num = job.get("num").toString();
			    listId.add(Integer.parseInt(id));
			    ProductInfo info = this.getProdInfoSum(id,listProductInfo);
				if (info != null) {
					if (info.getStockQty() < Integer.parseInt(num)) {
						strName = info.getName();
						break;
					}
				}
			}
	    }
		return strName;
    }
	/**
	 * 判断积分是否可用
	 * @param dataLsit
	 * @return
	 */
	private boolean checkProductInfoSalePoints(JSONArray dataLsit,int avaPoints,List<ProductInfo> listProductInfo){
		boolean flag = true;
		int sunPoints = 0;//订单总积分
		if(dataLsit!=null){
			for(int i=0;i<dataLsit.size();i++){
				JSONObject job =    dataLsit.getJSONObject(i);
			    String id = job.get("id").toString();
			    String num = job.get("num").toString();
			    ProductInfo info = this.getProdInfoSum(id,listProductInfo);
			    int salePoints = 0;
			    if(info!=null){
			    	salePoints = info.getSalePoints();//销售积分
			    }
			    sunPoints += this.sunSalePoints(num,salePoints);
			}
		}
		if (sunPoints > avaPoints) {
			flag = false;
		}
		return flag;
	}
	/**
	 * 查找相同的商品订单
	 * @param prodInfoId
	 * @param listProductInfo
	 * @return
	 */
	private ProductInfo getProdInfoSum(String prodInfoId,List<ProductInfo> listProductInfo){
		ProductInfo productInfo = new ProductInfo();
		if(listProductInfo.size()>0){
			for(ProductInfo fo:listProductInfo){
				String pid = String.valueOf(fo.getId());
				if(prodInfoId.equals(pid)){
					productInfo = fo;					
				}
			}
		}
		return productInfo;				
	}
	/**
	 * 处理订单总积分
	 * @param num
	 * @param salePoints
	 * @return
	 */
	private int sunSalePoints(String num, int salePoints) {
		int numInt = Integer.parseInt(num);
		return numInt*salePoints;
	}

	/***
	 * 收货地址维护(积分商城)
	 * @param appId
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "addressMaintain/{appId}",method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object addressMaintain(@PathVariable("appId") String appId,@RequestBody Map<String, Object> map, HttpServletRequest request){
		String openId = map.get("openId").toString();
		CustShippingDTO dto = new CustShippingDTO();
		CustShipping custShipping = custShippingService.queryCustShipping(appId,openId);
		if (map.containsKey("address") && map.containsKey("city") && map.containsKey("district")
				&& map.containsKey("name") && map.containsKey("phone") && map.containsKey("province")) {
			String address = map.get("address").toString();
			String city = map.get("city").toString();	
			String district = map.get("district").toString();
			String name = map.get("name").toString();
			String phone = map.get("phone").toString();
			String province = map.get("province").toString();		
			
			if(StringUtil.isNotEmpty(address)&&StringUtil.isNotEmpty(city)&&StringUtil.isNotEmpty(district)&&StringUtil.isNotEmpty(name)&&StringUtil.isNotEmpty(phone)&&StringUtil.isNotEmpty(province)){
				if(custShipping!=null){
					CustShipping cp = new CustShipping();
					cp.setId(custShipping.getId());
					cp.setCustExId(custShipping.getCustExId());
					cp.setConsigneeName(name);
					cp.setMobile(phone);
					cp.setTelephone(custShipping.getTelephone());
					cp.setProvince(province);
					cp.setCity(city);
					cp.setDistrict(district);
					cp.setTown(custShipping.getTown());
					cp.setDetailAddress(address);
					cp.setIsDefault(custShipping.getIsDefault());
					cp.setCreatedTime(custShipping.getCreatedTime());
					cp.setLastModifiedTime(custShipping.getLastModifiedTime());
					custShippingService.updateCustShipping(cp);
					return new AccessResponse<Object>("0", "成功", cp);
				}else{
					custShippingService.insertCustShipping(openId,appId,address,city,district,name,phone,province);
					return new AccessResponse<Object>("0", "成功");
				}		
			}else{
				if(custShipping!=null){
					dto = new CustShippingDTO();
					dto.setAddress(custShipping.getDetailAddress());
					dto.setCity(custShipping.getCity());
					dto.setDistrict(custShipping.getDistrict());
					dto.setName(custShipping.getConsigneeName());
					dto.setPhone(custShipping.getMobile());
					dto.setProvince(custShipping.getProvince());
					return new AccessResponse<Object>("0", "ok", dto);
				}else{
					dto = new CustShippingDTO();
					dto.setAddress("");
					dto.setCity("");
					dto.setDistrict("");
					dto.setName("");
					dto.setPhone("");
					dto.setProvince("");
					return new AccessResponse<Object>("0", "ok", dto);
				}				
			}		
		}
		return new AccessResponse<Object>("0", "ok");
	}
	/***
	 * 物流跟踪(积分商城)
	 * @param map
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value = "logisticsTrack/{appId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object logisticsTrack(@PathVariable("appId") String appId,@RequestBody Map<String, Object> map, HttpServletRequest request) throws IOException {
		//String type = map.get("type").toString();
		String postid = map.get("postid").toString();
		CustItemRecord 	ItemRecord = custItemRecordService.findCustItemRecordById(postid);
		if(StringUtil.isNotEmpty(ItemRecord.getShippingNo())){
			String url = "http://www.kuaidi100.com/query?type=" + ItemRecord.getShipperCode() + "&postid=" + ItemRecord.getShippingNo() + "";
			URL kd = new URL(url);
			BufferedReader in = new BufferedReader(new InputStreamReader(kd.openStream(),"UTF-8"));
			String inputLine;
			StringBuffer sb = new StringBuffer();
			while ((inputLine = in.readLine()) != null){
				sb.append(inputLine);
			}
			in.close();
			JSONObject json = (JSONObject) JSONObject.parse(sb.toString());
			json.put("com", this.logisticsNameMap().get(json.get("com").toString()));
			return new AccessResponse<Object>("0", "ok", json);
		}else{
			return new AccessResponse<Object>("0", "ok", "没有物流信息(物流单号缺失)");
		}
	}
	/***
	 * 积分商城商品分类搜索
	 * @param appId
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "queryProductInfoType/{appId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object queryProductInfoType(@PathVariable("appId") String appId,@RequestBody Map<String, Object> map, HttpServletRequest request){
		List<ProductInfoIntegralDTO> dtoList = new ArrayList<ProductInfoIntegralDTO>();
		String sPageIndex= map.get("pageIndex").toString();
		int pageIndex = ConvertUtils.getInt(sPageIndex);
		int pageSize = 10;
		map.put("appId", appId);
		Page page = new Page();
		page.setCurrentResult(pageIndex);
		page.setShowCount(pageSize);
		page.setMap(map);
	
		String type = map.get("type").toString();//分类
		String ordertype = map.get("ordertype").toString();//分类
		String reorder = map.get("reorder").toString();//排序		
		List<ProductInfo> list = productInfoService.queryProductInfoClassify(page,type,ordertype,reorder);
		if(list.size()>0){
			for(ProductInfo productInfo:list){
				ProductInfoIntegralDTO dto = new ProductInfoIntegralDTO();
				dto.setId(productInfo.getId());
				dto.setPrice(String.valueOf(productInfo.getSalePoints()));
				dto.setTitle(productInfo.getName());
				dto.setImg(productInfo.getImg());
				dto.setType(String.valueOf(productInfo.getProdType()));
				dtoList.add(dto);
			}
		}
		return new AccessResponse<Object>("0", "成功", dtoList);
	}
	/***
	 * 热门兑换商品
	 * @param appId
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "hotProductInfo/{appId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object hotProductInfo(@PathVariable("appId") String appId,@RequestBody Map<String, Object> map, HttpServletRequest request){
		List<ProductInfoIntegralDTO> dtoList = new ArrayList<ProductInfoIntegralDTO>();
		if (!map.containsKey("num")) {
			return this.getError("num不能为空");
		}
		int num = Integer.parseInt(map.get("num").toString());//显示多少条
		List<ProductInfo> list = productInfoService.queryProductInfoHotList(appId,num);
		if(list.size()>0){
			for(ProductInfo productInfo:list){
				ProductInfoIntegralDTO dto = new ProductInfoIntegralDTO();
				dto.setId(productInfo.getId());
				dto.setPrice(String.valueOf(productInfo.getSalePoints()));
				dto.setTitle(productInfo.getName());
				dto.setImg(productInfo.getImg());
				dto.setType(String.valueOf(productInfo.getProdType()));
				dtoList.add(dto);
			}
		}
		return new AccessResponse<Object>("0", "成功", dtoList);
	}
	/**
	 * 轮播图(积分商城)
	 * @param appId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "queryBannerInfo/{appId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object queryBannerInfo(@PathVariable("appId") String appId,HttpServletRequest request){
		List<BannerInfoDTO>  listBan = new ArrayList<BannerInfoDTO>();
		List<BannerInfo> list = bannerInfoService.findBannerInfo(appId);
		if(list.size()>0){
			for(BannerInfo ban:list){
				BannerInfoDTO dto = new BannerInfoDTO();
				dto.setImg(ban.getPicUrl());
				dto.setUrl(ban.getLinkUrl());
				listBan.add(dto);
			}
		}
		return new AccessResponse<Object>("0", "成功", listBan);
	}
	/***
	 * 确认订单(修改订单状态)
	 * @param appId
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "confirmOrder/{appId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public  Object  confirmOrder(@PathVariable("appId") String appId,@RequestBody Map<String, Object> map,HttpServletRequest request){
		if (!map.containsKey("id")) {
			return this.getError("id不能为空");
		}
		String id = map.get("id").toString();
		custItemRecordService.updateCustItemRecordOrderStatus(id);
		return new AccessResponse<Object>("0", "成功");
	}
	/***
	 * 初始化物流名称
	 * @param code
	 * @return
	 */
	public Map<String,String> logisticsNameMap(){
		Map<String,String> map = new HashMap<String, String>();
		map.put("shunfeng", "顺丰快递");
		map.put("ems", "EMS快递");
		map.put("shengtong", "申通快递");
		map.put("yuantong", "圆通快递");
		map.put("zhongtong", "中通快递");
		map.put("yunda", "韵达快递");
		map.put("baishihuitong", "百世汇通快递");
		map.put("zaijisong", "宅急送快递");
		map.put("tiantian", "天天快递");
		map.put("debangwuliu", "德邦物流快递");
		map.put("xinbangwuliu", "新邦物流快递");
		map.put("quanfeng", "全峰快递");
		map.put("shenghui", "盛辉快递");
		map.put("zhongtie", "中铁快递");
		return map;
	}
}
